<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script src="../axios.js"></script>
    <script>
      function myAxios(config) {
        return new Promise((resolve, reject) => {
          const { url, method, data, params } = config
          const xhr = new XMLHttpRequest()
          if (method.toUpperCase() === 'GET') {
            const str = setPro(params)
            xhr.open('GET', params ? url + '?' + str : url)
            xhr.send()
          } else {
            xhr.open('post', url)
            const flag =
              Object.prototype.toString.call(data) === '[object Object]'
            xhr.setRequestHeader(
              'Content-Type',
              flag ? 'application/json' : 'application/x-www-form-urlencoded'
            )
            xhr.send(flag ? JSON.stringify(data) : data)
          }
          xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
              if (xhr.status >= 200 && xhr.status < 300) {
                resolve(JSON.parse(xhr.responseText))
              } else {
                reject('请求失败，失败原因是' + xhr.status)
              }
            }
          }
        })
      }
      function setPro(data) {
        const arr = []
        for (let k in data) {
          let str = k + '=' + data[k]
          arr.push(str)
        }
        return arr.join('&')
      }
      myAxios({
        url: 'http://ajax-api.itheima.net/api/city',
        method: 'GET',
        params: { pname: '浙江省' },
      }).then((res) => console.log(res))
      myAxios({
        url: 'http://ajax-api.itheima.net/api/area?pname=浙江省&cname=杭州市',
        method: 'GET',
      }).then((res) => console.log(res))
      myAxios({
        url: 'http://ajax-api.itheima.net/api/login',
        method: 'POST',
        data: { username: 'admin', password: '123456' },
      }).then((res) => console.log(res))
      myAxios({
        url: 'http://ajax-api.itheima.net/api/login',
        method: 'POST',
        data: 'username=admin&password=123456',
      }).then((res) => console.log(res))
      //使用async，await方法
      const fn = async () => {
        const send = await myAxios({
          url: 'http://ajax-api.itheima.net/api/city',
          method: 'GET',
          params: { pname: '浙江省' },
        })
        console.log(send)
        return send
      }
      fn()
    </script>
  </body>
</html>
